package lab.jsp;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lab.bmp.studio.Studio;
import lab.bmp.studio.StudioPK;
import lab.domain.SoundRecordingStudio;

/**
 *
 * @author Smike
 */
public class EditStudio extends AbstractJSP<Studio> {

    public static final String ID = "id";
    public static final String NAME = "name";
    Studio studio;

    @Override
    public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // do nothing
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter(ID);
        if (id != null) {
            int value = Integer.valueOf(id);
            if (value >= 0) {
                studio = dao.findStudio(new StudioPK(value));
            }
        } else {
            studio = null;
        }
        super.doGet(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter(ID);
        if (id != null) {
            int value = Integer.valueOf(id);
            if (value >= 0) {
                studio = (Studio) PortableRemoteObject.narrow(dao.findStudio(new StudioPK(value)), Studio.class);
            }
        } else {
            throw new IllegalArgumentException();
        }
        try {
            if (request.getParameter("save") != null) {
                String name = request.getParameter(NAME);
                if (studio != null) {
                    studio.setName(name);
                } else {
                    SoundRecordingStudio s = new SoundRecordingStudio();
                    dao.insertStudio(s);
                }
            } else if (request.getParameter("delete") != null) {
                if (studio != null) {
                    studio.remove();
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(EditStudio.class.getName()).log(Level.SEVERE, null, ex);
        }
        response.sendRedirect("studios.jsp");
    }

    @Override
    protected Studio getData() {
        return studio;
    }
}
